const router = require("express").Router();
const sql = require("../mysql");
const Opportunity = require("../mysql/collection/Opportunity");
const uuid = require("uuid");

/**
 * @api {GET} /admin/crm/opportunities 获取商机列表
 * @apiName GetOpportunities
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [stage] 商机阶段筛选
 * @apiParam {String} [status] 商机状态筛选
 * @apiParam {String} [assignedTo] 负责人筛选
 * @apiParam {String} [keyword] 关键词搜索(标题)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 商机列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/opportunities", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, stage, status, assignedTo, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (stage) query.stage = stage;
    if (status) query.status = status;
    if (assignedTo) query.assignedTo = assignedTo;
    if (keyword) {
      query.title = { $regex: keyword, $options: 'i' };
    }
    
    const total = await Opportunity.countDocuments(query);
    const list = await Opportunity.find(query)
      .populate('customerId', 'name company phone')
      .populate('leadId', 'name company phone')
      .populate('assignedTo', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取商机列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取商机列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/opportunities 创建商机
 * @apiName CreateOpportunity
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {String} title 商机标题
 * @apiParam {String} [customerId] 关联客户ID
 * @apiParam {String} [leadId] 关联线索ID
 * @apiParam {Number} value 商机价值
 * @apiParam {String} [stage] 商机阶段
 * @apiParam {Number} [probability] 成交概率
 * @apiParam {Date} [expectedCloseDate] 预计成交日期
 * @apiParam {String} [description] 商机描述
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 商机数据
 */
router.post("/opportunities", async (req, res) => {
  try {
    const opportunityData = {
      ...req.body,
      opportunityId: "OPP_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase()
    };
    
    const opportunity = await Opportunity.create(opportunityData);
    const populatedOpportunity = await Opportunity.findById(opportunity._id)
      .populate('customerId', 'name company phone')
      .populate('leadId', 'name company phone')
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "创建商机成功",
      data: populatedOpportunity
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建商机失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/opportunities/:id 获取商机详情
 * @apiName GetOpportunityDetail
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {String} id 商机ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 商机详情
 */
router.get("/opportunities/:id", async (req, res) => {
  try {
    const opportunity = await Opportunity.findById(req.params.id)
      .populate('customerId', 'name company phone')
      .populate('leadId', 'name company phone')
      .populate('assignedTo', 'adminname');
    
    if (!opportunity) {
      return res.send({
        code: "404",
        message: "商机不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取商机详情成功",
      data: opportunity
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取商机详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/opportunities/:id 更新商机信息
 * @apiName UpdateOpportunity
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {String} id 商机ID
 * @apiParam {String} [title] 商机标题
 * @apiParam {String} [customerId] 关联客户ID
 * @apiParam {String} [leadId] 关联线索ID
 * @apiParam {Number} [value] 商机价值
 * @apiParam {String} [stage] 商机阶段
 * @apiParam {Number} [probability] 成交概率
 * @apiParam {Date} [expectedCloseDate] 预计成交日期
 * @apiParam {String} [description] 商机描述
 * @apiParam {String} [status] 商机状态
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的商机数据
 */
router.put("/opportunities/:id", async (req, res) => {
  try {
    const opportunity = await Opportunity.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('leadId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!opportunity) {
      return res.send({
        code: "404",
        message: "商机不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新商机信息成功",
      data: opportunity
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新商机信息失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/opportunities/:id/close 关闭商机
 * @apiName CloseOpportunity
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {String} id 商机ID
 * @apiParam {String} result 关闭结果(成交/失败)
 * @apiParam {String} [reason] 关闭原因
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 关闭后的商机数据
 */
router.post("/opportunities/:id/close", async (req, res) => {
  try {
    const { result, reason } = req.body;
    
    if (!['成交', '失败'].includes(result)) {
      return res.send({
        code: "400",
        message: "关闭结果只能是'成交'或'失败'"
      });
    }
    
    const updateData = {
      status: result === '成交' ? '已成交' : '已失败',
      stage: result === '成交' ? '已成交' : '已失败',
      probability: result === '成交' ? 100 : 0,
      closeReason: reason || '',
      closeDate: new Date()
    };
    
    const opportunity = await Opportunity.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('leadId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!opportunity) {
      return res.send({
        code: "404",
        message: "商机不存在"
      });
    }
    
    res.send({
      code: "200",
      message: `商机${result}成功`,
      data: opportunity
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "关闭商机失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/opportunities/:id 删除商机
 * @apiName DeleteOpportunity
 * @apiGroup CRM-Opportunity
 *
 * @apiParam {String} id 商机ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/opportunities/:id", async (req, res) => {
  try {
    const opportunity = await Opportunity.findByIdAndDelete(req.params.id);
    
    if (!opportunity) {
      return res.send({
        code: "404",
        message: "商机不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "删除商机成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除商机失败",
      error: error.message
    });
  }
});

module.exports = router;